package com.csnf.hymall.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 基础servlet
 */
public abstract class BaseServlet extends HttpServlet {
    protected Logger logger = LogManager.getLogger(HttpServlet.class);
    HttpSession session = null;
    String action = null;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session = req.getSession();
        action = req.getParameter("action");
        if (action == null) {
            logger.info("action为空，返回管理员登陆页");
            skipToPage(req, resp, "admin/login");
        } else {
              doService(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        service(req, resp);
    }

    protected abstract void doService(HttpServletRequest req, HttpServletResponse resp);

    protected void skipToPage(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
        logger.info("跳转至" + page);
        request.getRequestDispatcher("/page/" + page).forward(request, response);
    }

    protected void initRequest(HttpServletRequest request, Map<String, Object> reqMap) {
        //循环map 赋值到 request
        for (String key : reqMap.keySet()) {
            request.setAttribute(key, reqMap.get(key));
        }
        logger.info("初始化请求参数完成");
    }

    protected void returnJson(HttpServletResponse response, Object object) throws IOException {
        try {
//            String  json = JSON.toJSONString(object);
            JSONObject jsonObject = (JSONObject) JSON.toJSON(object);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(jsonObject.toJSONString());
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected Object checkAdmin(HttpSession session) {
        Object o = session.getAttribute("adminId");
        if (o == null) {
            logger.info("无管理权限，返回管理员登陆页");
            return null;
        }
        logger.info("当前登录管理员ID：{}", o);
        return o;
    }

    //检查用户是否登录
    protected Object checkUser(HttpSession session) {
        Object o = session.getAttribute("userId");
        if (o == null) {
            logger.info("用户未登录");
            return null;
        }
        logger.info("用户已登录，用户ID：{}", o);
        return o;
    }

    /**
     * 获取参数 如果为空 返回默认值
     *
     * @param req
     * @param clazz
     * @param paramName
     * @param defaultValue
     * @param <T>
     * @return
     */
    protected <T> T getParamsDefault(HttpServletRequest req, Class<T> clazz, String paramName, T defaultValue) {
        String param = req.getParameter(paramName);
        if (param == null || param.isEmpty()) {
            return defaultValue;
        }
        try {
            Constructor<T> constructor = clazz.getConstructor(String.class);
            return constructor.newInstance(param);
        } catch (Exception e) {
            return defaultValue;
        }
    }

}
